package com.example.weight.householdWaste;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HouseholdWasteMaintainActivity extends AppCompatActivity {

    private TextView dateText;

    private CheckBox gudingzhoucheng, jiayou, liantiao, chuchen,
            gCheck, jCheck, lCheck, cCheck;

    private LinearLayout gdzc, jy, ltjy, cc;

    private EditText gdzcText, jyText, ltjyText, ccText;

    private String name, role, fName, factory;

    private Map<String, String> fromIdMap;

    private RequestQueue queue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_household_waste_maintain);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");
        role = previousIntent.getStringExtra("role");
        fName = previousIntent.getStringExtra("fName");

        TitleBar titleBar = findViewById(R.id.hhw_maintain_plan_nav_titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

        dateText = findViewById(R.id.hhw_date);
        gudingzhoucheng = findViewById(R.id.hhw_gudingzhoucheng);
        jiayou = findViewById(R.id.hhw_jiayou);
        liantiao = findViewById(R.id.hhw_liantiaogelianjiebuweijiayou);
        chuchen = findViewById(R.id.hhw_qinglichuchen);
        gCheck = findViewById(R.id.hhw_gudingzhoucheng_check);
        jCheck = findViewById(R.id.hhw_jiayou_check);
        lCheck = findViewById(R.id.hhw_liantiaogelianjiebuweijiayou_check);
        cCheck = findViewById(R.id.hhw_qinglichuchen_check);
        gdzc = findViewById(R.id.hhw_gdzc);
        gdzcText = findViewById(R.id.hhw_gdzc_text);
        jy = findViewById(R.id.hhw_jy);
        jyText = findViewById(R.id.hhw_jy_text);
        ltjy = findViewById(R.id.hhw_ltjy);
        ltjyText = findViewById(R.id.hhw_ltjy_text);
        cc = findViewById(R.id.hhw_cc);
        ccText = findViewById(R.id.hhw_cc_text);

        // 显示当前日期
        Date date = new Date();
        String strDateFormat = "yyyy年 MM月 dd日";
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        dateText.setText(dateText.getText().toString().concat(sdf.format(date)));

        fromIdMap = new HashMap<>();

        queue = Volley.newRequestQueue(this);

        // 初始化表单
        switch (fName) {
            // 固定轴承+加油+链条各连接部位加油
            case "破袋机进料板链":
            case "瓶类分离机":
            case "瓶类分拣板链":
            case "塑料分离机进料板链":
                chuchen.setVisibility(View.GONE);
                cCheck.setVisibility(View.GONE);
                cc.setVisibility(View.GONE);
                setCheckStatus(gudingzhoucheng, gCheck);
                setCheckStatus(jiayou, jCheck);
                setCheckStatus(liantiao, lCheck);
                if (role.equals("操作人")) {
                    // 登录身份是操作人
                    gCheck.setEnabled(false);
                    jCheck.setEnabled(false);
                    lCheck.setEnabled(false);
                }
                break;
            // 链条各连接部位加油
            case "生活垃圾分离机长料输送螺旋":
                gudingzhoucheng.setVisibility(View.GONE);
                gCheck.setVisibility(View.GONE);
                gdzc.setVisibility(View.GONE);
                jiayou.setVisibility(View.GONE);
                jCheck.setVisibility(View.GONE);
                jy.setVisibility(View.GONE);
                chuchen.setVisibility(View.GONE);
                cCheck.setVisibility(View.GONE);
                cc.setVisibility(View.GONE);
                setCheckStatus(liantiao, lCheck);
                if (role.equals("操作人")) {
                    // 登录身份是操作人
                    lCheck.setEnabled(false);
                }
                break;
            // 清理除尘
            case "监控系统":
                gudingzhoucheng.setVisibility(View.GONE);
                gCheck.setVisibility(View.GONE);
                gdzc.setVisibility(View.GONE);
                jiayou.setVisibility(View.GONE);
                jCheck.setVisibility(View.GONE);
                jy.setVisibility(View.GONE);
                liantiao.setVisibility(View.GONE);
                lCheck.setVisibility(View.GONE);
                ltjy.setVisibility(View.GONE);
                setCheckStatus(chuchen, cCheck);
                if (role.equals("操作人")) {
                    // 登录身份是操作人
                    cCheck.setEnabled(false);
                }
                break;
            // 其余（固定轴承+加油）
            default:
                liantiao.setVisibility(View.GONE);
                lCheck.setVisibility(View.GONE);
                ltjy.setVisibility(View.GONE);
                chuchen.setVisibility(View.GONE);
                cCheck.setVisibility(View.GONE);
                cc.setVisibility(View.GONE);
                setCheckStatus(gudingzhoucheng, gCheck);
                setCheckStatus(jiayou, jCheck);
                if (role.equals("操作人")) {
                    // 登录身份是操作人
                    gCheck.setEnabled(false);
                    jCheck.setEnabled(false);
                }
        }

        // 操作人填表
        gudingzhoucheng.setOnClickListener(v -> {
            if (gudingzhoucheng.isChecked()) {
                operatorAddForm(gudingzhoucheng, gdzcText.getText().toString());
            }
        });
        jiayou.setOnClickListener(v -> {
            if (jiayou.isChecked()) {
                operatorAddForm(jiayou, jyText.getText().toString());
            }
        });
        liantiao.setOnClickListener(v -> {
            if (liantiao.isChecked()){
                operatorAddForm(liantiao, ltjyText.getText().toString());
            }
        });
        chuchen.setOnClickListener(v -> {
            if (chuchen.isChecked()) {
                operatorAddForm(chuchen, ccText.getText().toString());
            }
        });

        // 检查人填表
        gCheck.setOnClickListener(v -> {
            if (gCheck.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(gudingzhoucheng.getText().toString())) != null)
                    examinerAddForm(fromId, gdzcText.getText().toString(), gCheck);
            }
        });
        jCheck.setOnClickListener(v -> {
            if (jCheck.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(jiayou.getText().toString())) != null)
                    examinerAddForm(fromId, jyText.getText().toString(), jCheck);
            }
        });
        lCheck.setOnClickListener(v -> {
            if (lCheck.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(liantiao.getText().toString())) != null)
                    examinerAddForm(fromId, ltjyText.getText().toString(), lCheck);
            }
        });
        cCheck.setOnClickListener(v -> {
            if (cCheck.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(chuchen.getText().toString())) != null)
                    examinerAddForm(fromId, ccText.getText().toString(), cCheck);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();

        Intent intent = new Intent();
        intent.putExtra("needRefresh", true);
        setResult(RESULT_OK, intent);
    }

    private void operatorAddForm(CheckBox checkBox, String comment) {
        String maintainContent = checkBox.getText().toString();
        AlertDialog alertDialog = new AlertDialog.Builder(this)
            .setTitle("确定提交吗？")
            .setCancelable(false)
            .setNegativeButton("取消", ((dialog, which) -> checkBox.setChecked(false)))
            .setPositiveButton("确定", (dialog, which) -> {
                checkBox.setEnabled(false);
                checkBox.setTextColor(Color.GREEN);
                String url = Config.url + "/shlj/equipmentMaintenance/add_recorder";
                StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    String code = jsonObject.getString("code");

                                    if (code.startsWith("2"))
                                        Toast.makeText(HouseholdWasteMaintainActivity.this,
                                                "保存成功", Toast.LENGTH_SHORT).show();
                                    else
                                        Toast.makeText(HouseholdWasteMaintainActivity.this,
                                                "保存失败", Toast.LENGTH_SHORT).show();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(HouseholdWasteMaintainActivity.this,
                                "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String> map=new HashMap<>();
                        map.put("equipmentName", fName);
                        map.put("operator", name);
                        map.put("method", maintainContent);
                        map.put("remarks", comment);
                        map.put("factory", factory);
                        return map;
                    }
                };
                stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                        DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                queue.add(stringRequest);
            }).show();
        // 设置“设置按钮”的边距，主要是为了不改变公用button按钮
//        Button negativeButton = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
//        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) negativeButton.getLayoutParams();
//        layoutParams.setMargins(0, 0, 40, 0);//4个参数按顺序分别是左上右下
//        negativeButton.setLayoutParams(layoutParams);
    }

    private void setCheckStatus(CheckBox operatorCB, CheckBox examinerCB) {
        String maintainContent = operatorCB.getText().toString();
        String url = Config.url + "/shlj/equipmentMaintenance/getlatest";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONObject data = jsonObject.getJSONObject("data");
                                operatorCB.setChecked(true);
                                operatorCB.setEnabled(false);
                                operatorCB.setTextColor(Color.GREEN);
                                if (role.equals("操作人"))
                                    setRemarks(operatorCB, data.getString("remarks"));
                                else
                                    setRemarks(operatorCB, data.getString("result"));

                                String examiner = data.getString("examiner");
                                if (!examiner.equals("") && !examiner.equals("null")) {
                                    // 检查人已检查某项，该项不可再检查
                                    examinerCB.setChecked(true);
                                    examinerCB.setEnabled(false);
                                    examinerCB.setTextColor(Color.GREEN);
                                } else {
                                    // 若存在检查人未检查项，将其添加到formIdList中
                                    fromIdMap.put(maintainContent, data.getString("id"));
                                }
//                                if (role.equals("检查人")) {
//
//                                }
                            } else {
                                if (role.equals("检查人")) {
                                    // 如果操作人未保养，检查人不可检查
//                                    Log.d("zys", maintainContent);
                                    operatorCB.setEnabled(false);
                                    examinerCB.setEnabled(false);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(HouseholdWasteMaintainActivity.this,
                        "失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map=new HashMap<>();
                map.put("equipmentName", fName);
                map.put("maintenanceContent", maintainContent);
                map.put("factory", factory);
                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

    private void examinerAddForm(String formId, String comment, CheckBox checkBox) {
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle("操作人结论是否正确？若有误请在备注填写问题")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) -> checkBox.setChecked(false)))
                .setPositiveButton("确定", (dialog, which) -> {
                    checkBox.setEnabled(false);
                    checkBox.setTextColor(Color.GREEN);
                    String url = Config.url + "/shlj/equipmentMaintenance/add_examiner";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");

                                        if (code.startsWith("2"))
                                            Toast.makeText(HouseholdWasteMaintainActivity.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(HouseholdWasteMaintainActivity.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(HouseholdWasteMaintainActivity.this,
                                    "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> map=new HashMap<>();
                            map.put("id", formId);
                            map.put("examiner", name);
                            map.put("result", comment);
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                }).show();
        // 设置“设置按钮”的边距，主要是为了不改变公用button按钮
//        Button negativeButton = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
//        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) negativeButton.getLayoutParams();
//        layoutParams.setMargins(0, 0, 40, 0);//4个参数按顺序分别是左上右下
//        negativeButton.setLayoutParams(layoutParams);
    }

    private void setRemarks(CheckBox checkBox, String remarks) {
        switch (checkBox.getText().toString()) {
            case "固定轴承":
                gdzcText.setText(remarks);
                break;
            case "加油":
                jyText.setText(remarks);
                break;
            case "链条各连接部位加油":
                ltjyText.setText(remarks);
                break;
            case "清理除尘":
                ccText.setText(remarks);
                break;
            default:
        }
    }
}